package com.openroom.ui;

import java.awt.Event;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.apache.pivot.util.concurrent.Task;
import org.apache.pivot.util.concurrent.TaskExecutionException;
import org.apache.pivot.wtk.ApplicationContext;
import org.apache.pivot.wtk.Label;
import org.apache.pivot.wtk.Meter;

import com.jphotomanager.io.ImageImporter;
import com.mortennobel.imagescaling.ResampleOp;
import com.openroom.db.DBHelper;
import com.openroom.event.ApplicationEvent;
import com.openroom.event.EventManager;
import com.openroom.event.EventType;
import com.openroom.model.Folder;
import com.openroom.model.ModelLocator;
import com.openroom.model.Photograph;

public class ThumbnailMakingTask extends Task<Void> {

	protected File directory;

	protected int fileCounter = 0;

	protected List<File> listFiles;

	protected double percentage = 0;

	protected Folder folder;

	protected Meter meter;

	protected Label label;

	public ThumbnailMakingTask() {
	}

	public ThumbnailMakingTask(Meter meter, Label label, Folder folder) {
		this.folder = folder;
		Collection<File> listFiles2 = FileUtils.listFiles(
				new File(folder.getLocalPath()),
				SupportedFileFilter.SUPPORTED_FILE_EXTENSION, true);
		listFiles = new ArrayList<File>(listFiles2);
		this.meter = meter;
		this.label = label;
	}

	@Override
	public Void execute() throws TaskExecutionException {
		int totalFiles = listFiles.size();
		if (totalFiles == 0)
			return null;
		ModelLocator.getInstance().setTotalImageBeingImported(totalFiles);
		// Simulate a long-running operation
		percentage = ((double) fileCounter) / totalFiles;
		if (fileCounter > totalFiles)
			return null;
		ModelLocator.getInstance().getAllShowingImage().clear();
		EventManager.getInstance().publishEvent(
				new ApplicationEvent(EventType.ALL_SHOWING_IMAGE_CHANGED));
		for (File file : listFiles) {
			try {
				if (abort)
					return null;
				final File file2 = listFiles.get((int) fileCounter++);
				Photograph image = createThumbnail(file);
				if(fileCounter <= ModelLocator.MAX_IMAGE_PER_PAGE){
					ModelLocator.getInstance().importImageToWorkspace(image);
				}
				// Update the meter on the UI thread
				ApplicationContext.queueCallback(new Runnable() {
					@Override
					public void run() {
						if (meter != null && meter.isVisible()) {
							meter.setPercentage((double) percentage);
							label.setText("Importing " + file2.getName());
						}
					}
				});
				percentage = ((double) fileCounter) / totalFiles;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		DBHelper.getInstance().commit();
		return null;
	}

	protected Photograph createThumbnail(File file) {
		Photograph image = ImageImporter.importFile(MainWindow.TEMP_DIR, file);
		return image;
	}

}